package com.yanxu;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-06-05-2025
 * @Description: 搜索者，用于搜索服务支持方
 */
public class UDPSearcher {
    public static void main(String[] args) throws IOException {
        System.out.println("UDP Searcher started");

        /* 创建 DatagramSocket对象，当前是作为搜索方，无需监听固定端口，因此无需指定端口，让系统自动分配即可 */
        DatagramSocket datagramSocket = new DatagramSocket();

        /* 构建发送实体 */
        // 消息内容
        byte[] buf = "hello world".getBytes();
        DatagramPacket requestPacket = new DatagramPacket(buf, buf.length);
        // 目标ip
        requestPacket.setAddress(InetAddress.getByName("127.0.0.1"));
        // 目标端口
        requestPacket.setPort(20000);

        /* 发送 */
        datagramSocket.send(requestPacket);

        /* 接收数据 */
        byte[] receiveBuf = new byte[1024];
        DatagramPacket sendPacket = new DatagramPacket(receiveBuf, 0, receiveBuf.length);
        datagramSocket.receive(sendPacket);
        int length = sendPacket.getLength();
        String msg = new String(receiveBuf, 0, length);
        System.out.println("UDP Searcher received: " + msg);


    }
}